package com.shang.controller;

import com.shang.pojo.Users;
import com.shang.pojo.bo.ShopCartBO;
import com.shang.pojo.bo.UserBO;
import com.shang.pojo.vo.UsersVO;
import com.shang.service.UserService;
import com.shang.utils.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Api(value = "注册登录",tags = {"用于注册登录的相关接口"})
@RestController
@RequestMapping("passport")
public class PassportController extends BaseController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisOperator redisOperator;

    @ApiOperation(value = "用户名是否存在",notes = "",httpMethod = "GET")
    @GetMapping("/usernameIsExist")
    public ShangJSONResult usernameIsExist(@RequestParam String username){
        //判断是否为空
        if (StringUtils.isBlank(username)){
            return ShangJSONResult.errorMsg("用户名不能为空");
        }
        //查找注册的用户名是否存在
        boolean isExist = userService.queryUsernameIsExist(username);
        if (isExist){
            return ShangJSONResult.errorMsg("用户名已经存在");
        }

        return ShangJSONResult.ok();
    }

    @ApiOperation(value = "用户注册",notes = "",httpMethod = "POST")
    @PostMapping("/regist")
    public ShangJSONResult regist(@RequestBody UserBO userBO,HttpServletRequest request,HttpServletResponse response){

        String username = userBO.getUsername();
        String password = userBO.getPassword();
        String confirmPassword = userBO.getConfirmPassword();

        if (StringUtils.isBlank(username) || StringUtils.isBlank(password) || StringUtils.isBlank(confirmPassword)){
            return ShangJSONResult.errorMsg("用户名或密码不能为空");
        }

        //查找注册的用户名是否存在
        boolean isExist = userService.queryUsernameIsExist(username);
        if (isExist){
            return ShangJSONResult.errorMsg("用户名已经存在");
        }

        if (password.length() < 6){
            return ShangJSONResult.errorMsg("密码不能少于6位");
        }

        if (!password.equals(confirmPassword)){
            return ShangJSONResult.errorMsg("密码不一致");
        }

        //Redis会话
        Users user = userService.createUser(userBO);
        UsersVO usersVO = conventUsersVO(user);

        CookieUtils.setCookie(request,response,"user",JsonUtils.objectToJson(usersVO),true);
        //生成用户TOKEN，存入Redis会话

        //同步购物车数据
        synchShopcartData(request,response,user.getId());

        return ShangJSONResult.ok();
    }


    @ApiOperation(value = "用户登录",notes = "",httpMethod = "POST")
    @PostMapping("/login")
    public ShangJSONResult login(@RequestBody UserBO userBO, HttpServletRequest request, HttpServletResponse response) throws Exception {

        String username = userBO.getUsername();
        String password = userBO.getPassword();

        if (StringUtils.isBlank(username) || StringUtils.isBlank(password)){
            return ShangJSONResult.errorMsg("用户名或密码不能为空");
        }

        Users users = userService.queryUserForLogin(username, MD5Utils.getMD5Str(password));

        if (users == null){
            return ShangJSONResult.errorMsg("用户名或密码不正确");
        }

        UsersVO usersVO = conventUsersVO(users);

        CookieUtils.setCookie(request,response,"user", JsonUtils.objectToJson(usersVO),true);

        //同步购物车数据
        synchShopcartData(request,response,users.getId());
        return ShangJSONResult.ok(users);
    }

    /**
     * 用户信息置空
     * @param users
     * @return
     */
    private Users setNullProperty(Users users){
        users.setPassword(null);
        users.setMobile(null);
        users.setEmail(null);
        users.setCreatedTime(null);
        users.setUpdatedTime(null);
        users.setBirthday(null);

        return users;

    }


    @ApiOperation(value = "用户退出",notes = "",httpMethod = "POST")
    @PostMapping("/logout")
    public ShangJSONResult logout(@RequestParam String userId, HttpServletRequest request, HttpServletResponse response){

        CookieUtils.deleteCookie(request,response,"user");
        //用户退出登录，清空购物车/会话信息
        redisOperator.del(REDIS_USER_TOKEN + ":" + userId);
        CookieUtils.deleteCookie(request,response,FOODIE_SHOPCART);

        return ShangJSONResult.ok();
    }

    /**
     * 注册登录成功后，同步cookie和redis中的购物车数据
     */
    private void synchShopcartData(HttpServletRequest request,HttpServletResponse response,String userId){

        //从redis中获取购物车信息
        String shopcartJsonRedis = redisOperator.get(FOODIE_SHOPCART + ":" + userId);
        //从cookie中获取购物车
        String shopcartStrCookie = CookieUtils.getCookieValue(request, FOODIE_SHOPCART, true);
        //定义待删除列表
        List<ShopCartBO> pendingDeleteList = new ArrayList<>();
        if (StringUtils.isNotBlank(shopcartJsonRedis)){
            if (StringUtils.isBlank(shopcartStrCookie)){
                redisOperator.set(FOODIE_SHOPCART + ":" + userId,shopcartStrCookie);
            }
        }else {
            if (StringUtils.isNotBlank(shopcartStrCookie)){
                List<ShopCartBO> shopCartBOListRedis = JsonUtils.jsonToList(shopcartJsonRedis, ShopCartBO.class);
                List<ShopCartBO> shopCartBOListCookie = JsonUtils.jsonToList(shopcartStrCookie, ShopCartBO.class);
                for (ShopCartBO redisShopcart : shopCartBOListRedis){
                    String redisSpecId = redisShopcart.getSpecId();
                    for (ShopCartBO cookieShopcart : shopCartBOListCookie){
                        String cookieSpecId = cookieShopcart.getSpecId();
                        if (redisSpecId.equals(cookieSpecId)){
                            //覆盖购买数量，不累加
                            redisShopcart.setBuyCounts(cookieShopcart.getBuyCounts());
                            pendingDeleteList.add(cookieShopcart);
                        }
                    }
                }
                //从现有cookie中删除覆盖过的商品数据
                shopCartBOListCookie.removeAll(pendingDeleteList);
                //合并数据
                shopCartBOListRedis.addAll(shopCartBOListCookie);
                //更新cookie
                CookieUtils.setCookie(request,response,FOODIE_SHOPCART,JsonUtils.objectToJson(shopCartBOListRedis),true);
                //更新redis
                redisOperator.set(FOODIE_SHOPCART + ":" + userId,JsonUtils.objectToJson(shopCartBOListRedis));
            }else {
                CookieUtils.setCookie(request,response,FOODIE_SHOPCART,shopcartJsonRedis,true);
            }
        }

    }


}
